using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.Users.Commands;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.Users.CommandHandler;
public class ChangeEmailCommandHandler : IRequestHandler<ChangeEmailCommand, UserDto>
{
    private readonly IUserService _userService;

    public ChangeEmailCommandHandler(IUserService userService)
    {
        _userService = userService;
    }
    public async Task<UserDto> Handle(ChangeEmailCommand request, CancellationToken cancellationToken)
    {
        var userdto = await _userService.GetUserByIdAsync(request.userId);
        if (userdto == null) throw new Exception("用户无法找到");

        var user = UserAggregate.LoadFromPersistence(userdto.Id, userdto.UserName, userdto.Email, userdto.Roles.ToList());

        user.ChangeEmail(request.newEmail);

        var result = await _userService.UpdateUserAsync(user);
        if (result == null) throw new Exception("更新用户失败");
        return result;
    }
}